﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.Entity;
using CRM.BLL;
using System.Text;
using DP.Common;
using DP.Web.UI;

namespace CRM.Web.ClaimFormManage
{
    public partial class Assignment : Common.PageBase
    {
        T_USER_BLL bll = new T_USER_BLL();
        private T_DEPARTMENT_BLL dBll = new T_DEPARTMENT_BLL();
        private T_CLAIMFORM_BLL cfBll = new T_CLAIMFORM_BLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlDepartmentBinding();
                gvDataBinding();
                pageInit();
            }
        }

        private void pageInit()
        {
            lblClaimFormCount.Text = cfBll.GetCount(String.Format(" and (AssignedPersons is null or AssignedPersons = '' )")).ToString();
        }

        private void ddlDepartmentBinding()
        {
            StringBuilder sql = new StringBuilder();
            if(!UserLoginInfo.IsAdministrator())
            {
                sql.Append(" and BUSINESSDIVISIONCODE = '" + _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.Trim() + "'");
            }
            sql.Append(String.Format(" and ISCENTER = '{0}' ", ((int)DepartmentType.呼叫中心).ToString()));
            sql.Append(" and DepartmentID in (select DepartmentID from T_User ) ");

            ddlDepartment.DataSource = dBll.GetList(sql.ToString());
            ddlDepartment.DataTextField = "DEPARTMENTNAME";
            ddlDepartment.DataValueField = "DEPARTMENTID";
            ddlDepartment.DataBind();

        }

        /// <summary>
        /// 生成查询条件字符串
        /// </summary>
        private StringBuilder GenerationSQLString()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(" and (ISSYSTEMADMIN <> '1' or ISSYSTEMADMIN is null) ");
            sql.Append(String.Format(" and DEPARTMENTID = '{0}' ", ddlDepartment.SelectedValue));
            if (!UserLoginInfo.IsAdministrator())
            {
                sql.Append(" and BUSINESSDIVISIONCODE = '" + _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.Trim() + "'");
            }
            return sql;

        }

        /// <summary>
        /// 页面数据绑定
        /// </summary>
        private void gvDataBinding()
        {
            #region 查询条件字符串
            StringBuilder sql = GenerationSQLString();
            #endregion

            List<T_USER_Entity> list;

            //获取总的记录条数
            gvList.RecordCount = (int)bll.GetCount(sql.ToString());

            list = bll.GetList(sql.ToString(), gvList.SortConditions);

            gvList.DataSource = list;
            gvList.DataKeyNames = new string[] { "USERID", "UserName", "LoginName" };
            gvList.DataBind();

        }

        protected void btnAssign_Click(object sender, EventArgs e)
        {
            List<T_USER_Entity> list = GetSelected(gvList);
            int claimFormCount = StringHelper.ToInt(lblClaimFormCount.Text.Trim(), 0);
            int assignCount = StringHelper.ToInt(txtAssignCount.Text.Trim(), 0);
            int limited = 24;
            if (assignCount*list.Count > claimFormCount)
            {
                PageHelper.ShowMessage("需要分配的名单大小现在未分配的名单数!");
                return;
            }
            const string sqlUpdate = "update t_claimform set assignedpersons = '{0}' , assignedpersonname = '{1}', distributionpeople = '{2}', distributionpeoplename = '{3}', limited = '{4}', allocatedtime = sysdate  where claimformid in (select claimformid from (select t_claimform.*, rownum rn from t_claimform where (assignedpersons is null or assignedpersons = '') order by claimformid asc) t where t.rn <= {5}) ";

            try
            {
                foreach (T_USER_Entity en in list)
                {
                    cfBll._dal.ExecuteSQL(String.Format(sqlUpdate, en.USERID, en.USERNAME, _userLoginInfo.UserEntity.USERID, _userLoginInfo.UserEntity.USERNAME, limited, assignCount));
                }
                pageInit();
                PageHelper.ShowMessage("分配完成!");
            }
            catch (Exception ex)
            {
                PageHelper.ShowMessage("分配失败!");
            }

        }

        protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvDataBinding();
        }


        private List<T_USER_Entity> GetSelected(GridView gv)
        {
            List<T_USER_Entity> list = new List<T_USER_Entity>();
            if (gv == null) return list;
            T_USER_Entity entity;
            CheckBox cb;
            foreach (GridViewRow gvr in gv.Rows)
            {
                cb = gvr.FindControl("cbItem") as CheckBox;
                if (cb == null) continue;
                if(!cb.Checked) continue;
                entity = new T_USER_Entity();
                entity.USERID = StringHelper.ToInt(gv.DataKeys[gvr.RowIndex].Values["USERID"].ToString(), 0);
                entity.USERNAME = gv.DataKeys[gvr.RowIndex].Values["UserName"].ToString();
                entity.LOGINNAME = gv.DataKeys[gvr.RowIndex].Values["LoginName"].ToString();
                list.Add(entity);
            }
            return list;
        }

    }
}
